package com.example.zx.theline.lyjh.lyzjh;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.zx.theline.R;
import com.example.zx.theline.lyjh.lyrjh.SgrjhCxFragment;
import com.example.zx.theline.lyjh.lyzjh.pub.SgzjhCkshjlActivity;
import com.example.zx.theline.lyjh.lyzjh.pub.SgzjhShenheDetailActivity;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.ShzjhBean;
import Utils.BackHandlerHelper;
import Utils.DateUtil;
import Utils.MyToast;
import app.MyApplication;
import base.BaseFragment;
import bean.ZjhshSearchBean;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.SgzjhshSearchView;

/**
 * Update by Jianqi on 2017\8\25 0025.
 * <p>
 * 审核周计划
 */
public class ShzjhFragment extends BaseFragment implements View.OnClickListener, SHSwipeRefreshLayout.SHSOnRefreshListener {
    //UI
    private TextView leftTextView,prev,centerTextView1,centerTextView2,next,rightTextView;
    private SHSwipeRefreshLayout mSHSwipeRefreshLayout;
    private SHListView mSHListView;
    private TextView mFootTextView;
    //Data
    private int pageNumber = 0; //页号
    private ShzjhBean mShzjhBean; //该页面数据列表实体
    private List<ShzjhBean.RowsBean> mList;
    private MyAdapter mAdapter;
    //条件搜索
    private ZjhshSearchBean mSearchBean;
    private SgzjhshSearchView mSearchView;
    private String bh;

    public static boolean onStartRefresh = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_shzjh, container, false);

        leftTextView = (TextView) contentView.findViewById(R.id.leftTextView);
        prev = (TextView) contentView.findViewById(R.id.prev);
        centerTextView1 = (TextView) contentView.findViewById(R.id.centerTextView1);
        centerTextView2 = (TextView) contentView.findViewById(R.id.centerTextView2);
        next = (TextView) contentView.findViewById(R.id.next);
        rightTextView = (TextView) contentView.findViewById(R.id.rightTextView);

        mSearchView = (SgzjhshSearchView) contentView.findViewById(R.id.jhshsearchview);
        mSHSwipeRefreshLayout = (SHSwipeRefreshLayout) contentView.findViewById(R.id.SHSwipeRefreshLayout);
        mSHListView = (SHListView) contentView.findViewById(R.id.SHListView);
        View FootView = inflater.inflate(R.layout.refresh_view, null);
        mFootTextView = (TextView) FootView.findViewById(R.id.title);
        mSHSwipeRefreshLayout.setFooterView(FootView);
        //初始化模块
        InitData();
        InitSearchView();
        InitListen();
        return contentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (onStartRefresh) {
            requestShzjhList(0, 10, "refresh"); //刷新数据
            onStartRefresh = false;
        }
    }

    @Override
    protected void InitData() {

        mList = new ArrayList<>();
        mAdapter = new MyAdapter();
        mSHListView.setAdapter(mAdapter);
    }

    public void InitSearchView(){

        prev.setText("上一周");
        next.setText("下一周");

        date=DateUtil.startOfThisWeekToDate(date);
        date2=DateUtil.endOfThisWeekToDate(date2);
        upDateTitle();
        mSearchBean=new ZjhshSearchBean();
        setSearchBean();

    }
    @Override
    protected void InitListen() {
        leftTextView.setOnClickListener(this);
        centerTextView1.setOnClickListener(this);
        centerTextView2.setOnClickListener(this);
        rightTextView.setOnClickListener(this);
        prev.setOnClickListener(this);
        next.setOnClickListener(this);
        mSHSwipeRefreshLayout.setOnRefreshListener(this);
        mSearchView.setConfirmListener(new SgzjhshSearchView.OnClick() {
            @Override
            public void onConfirmListener(ZjhshSearchBean Util) {
                mSearchBean = Util;
                mSHSwipeRefreshLayout.startRefresh();
                requestShzjhList(0, 10, "refresh"); //展示最新数据
            }
        });
    }

    @Override
    protected void onFragmentFirstVisible() { //Fragment第一次加载的时候
        super.onFragmentFirstVisible();
        requestShzjhList(0, 10, ""); //初始化数据
    }

    @Override
    public void onRefresh() {
        requestShzjhList(0, 10, "refresh"); //刷新数据
    }

    @Override
    public void onLoading() {
        requestShzjhList(pageNumber, 10, "loadmore"); //加载数据
    }

    @Override
    public void onRefreshPulStateChange(float percent, int state) {
        switch (state) {
            case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                mSHSwipeRefreshLayout.setRefreshViewText("下拉刷新");
                break;
            case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                mSHSwipeRefreshLayout.setRefreshViewText("松开刷新");
                break;
            case SHSwipeRefreshLayout.START:
                mSHSwipeRefreshLayout.setRefreshViewText("正在刷新");
                break;
        }
    }

    @Override
    public void onLoadmorePullStateChange(float percent, int state) {
        switch (state) {
            case SHSwipeRefreshLayout.NOT_OVER_TRIGGER_POINT:
                mFootTextView.setText("上拉加载");
                break;
            case SHSwipeRefreshLayout.OVER_TRIGGER_POINT:
                mFootTextView.setText("松开加载");
                break;
            case SHSwipeRefreshLayout.START:
                mFootTextView.setText("正在加载...");
                break;
        }
    }

    @Override
    public boolean onBackPressed() { //处理自定义View，系统返回键
        if (mSearchView.getVisibility() == View.VISIBLE) {
            mSearchView.setVisibility(View.GONE);
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //日期选择
            case R.id.centerTextView1:
                TimePickerView.getInstance(getContext(),ShzjhFragment.this.date,new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        ShzjhFragment.this.date=date;
                        setSearchBean();
                        upDatedAndRefresh();
                        requestShzjhList(0, 10, "refresh");
                    }
                }).show();
                break;
            //日期选择
            case R.id.centerTextView2:
                TimePickerView.getInstance(getContext(),ShzjhFragment.this.date2,new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        ShzjhFragment.this.date2=date;
                        setSearchBean();
                        upDatedAndRefresh();
                        requestShzjhList(0, 10, "refresh");
                    }
                }).show();
                break;
            case R.id.leftTextView:
                getActivity().finish();
                break;
            case R.id.rightTextView:
                if (mSearchView.getVisibility() == View.GONE) {
                    mSearchView.setVisibility(View.VISIBLE);
                } else {
                    mSearchView.setVisibility(View.GONE);
                }
                break;
            case R.id.prev:
                butPrev();
                break;
            case R.id.next:
                butNext();
                break;

        }
    }

    //按钮上一周事件
    public void butPrev() {
        date = DateUtil.getAfterDayDate(date, -7);
        setSearchBean();
        upDatedAndRefresh();
    }

    //按钮下一周事件
    public void butNext() {
        date = DateUtil.getAfterDayDate(date, 7);
        setSearchBean();
        upDatedAndRefresh();
    }

    //更新标题栏日期并刷新列表数据
    public void upDatedAndRefresh() {
        upDateTitle();
        //刷新列表数据
        onRefresh();
    }

    //更新标题栏内容
    private void upDateTitle(){
        centerTextView1.setText(DateUtil.getYearAndMonthAndDay(date));
        centerTextView2.setText(DateUtil.getYearAndMonthAndDay (date2));
    }

    //设置搜索日期
    private void setSearchBean() {
        mSearchBean.setKsrq(DateUtil.getYearAndMonthAndDay(date));
        mSearchBean.setJsrq(DateUtil.getYearAndMonthAndDay(date2));
        mSearchView.setDefaultDate(mSearchBean);
    }

    //请求审核周计划的列表数据
    private void requestShzjhList(int pageNum, int pageSize, final String flag) {
        this.pageNumber = pageNum;
        pageNumber++;
        Map<String,String> map=new HashMap<>();
        map = setMap(map, mSearchBean);
        map.put("pageNumber", String.valueOf(pageNumber));
        map.put("pageSize", String.valueOf(pageSize));
        map.put("loginDwId", MyApplication.getmLoginUser().getUserUnitId());
        MyApplication.ShowWaitDialog(getContext());
        NetWorkApi.requestShzjhListData(map, new BaseCallBack<ShzjhBean>() {

                    @Override
                    public void Success(Call<ShzjhBean> call, Response<ShzjhBean> response) {
                        try {
                            mShzjhBean = response.body();
                            if (mShzjhBean.getMsg().equals("success")) {
                                if (mShzjhBean.getRows().size() > 0) {
                                    if (flag.equals("refresh")) { //判断是否是刷新，如果是刷新则将之前的List清空
                                        mList.clear();
                                    }
                                    mList.addAll(mShzjhBean.getRows()); //将请求到的数据添加到List集合中
                                    mAdapter.notifyDataSetChanged(); //刷新数据列表
                                } else {
                                    if (flag.equals("loadmore")) {
//                                        MyToast.showToast("暂无更多数据");
                                    } else {
                                        mList.clear();
                                        mAdapter.notifyDataSetChanged();
//                                        MyToast.showToast("暂无数据");
                                    }
                                }
                            } else {
                                MyToast.showNullObjectError(getContext());
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void Failure(Call<ShzjhBean> call, Throwable t) {
                        MyToast.showFail();
                    }

                    @Override
                    public void onFinally() {
                        switch (flag) {
                            case "refresh": //刷新
                                mSHSwipeRefreshLayout.finishRefresh();
                                break;
                            case "loadmore": //加载
                                mSHSwipeRefreshLayout.finishLoadmore();
                                break;
                        }
                    }
                }
        );
    }

    //审核周计划页面的适配器
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_zjhcx, null);
                holder = new ViewHolder();
                holder.yjhh = (TextView) convertView.findViewById(R.id.yjhh);
                holder.sgrq = (TextView) convertView.findViewById(R.id.sgrq);
                holder.lb = (TextView) convertView.findViewById(R.id.lb);
                holder.layout_blfh = (LinearLayout) convertView.findViewById(R.id.layout_blfh);
                holder.tablelayout = (LinearLayout) convertView.findViewById(R.id.tablelayout);
                holder.xm = (TextView) convertView.findViewById(R.id.xm);
                holder.hb = (TextView) convertView.findViewById(R.id.hb);
                holder.sgdd = (TextView) convertView.findViewById(R.id.sgdd);
                holder.sgxm = (TextView) convertView.findViewById(R.id.sgxm);
                holder.sgnr = (TextView) convertView.findViewById(R.id.sgnr);
                holder.sgjx = (TextView) convertView.findViewById(R.id.sgjx);
                holder.blfh = (TextView) convertView.findViewById(R.id.blfh);
                holder.sgdw = (TextView) convertView.findViewById(R.id.sgdw);
                holder.zt = (TextView) convertView.findViewById(R.id.zt);
                holder.mImageView = (ImageView) convertView.findViewById(R.id.mImageView);
                holder.tv_jhsh = (TextView) convertView.findViewById(R.id.tv_jhsh);
                holder.flagImg = (ImageView) convertView.findViewById(R.id.zhou_flag);
                holder.btnShlc = (TextView) convertView.findViewById(R.id.btn_shlc);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.btnShlc.setVisibility(View.GONE);
            holder.yjhh.setText(mList.get(position).getBh());
            holder.sgrq.setText(mList.get(position).getExsgrq());
            holder.lb.setText(mList.get(position).getLb() + "类");
            if (mList.get(position).getLb().equals("B")) {
                holder.lb.setTextColor(getResources().getColor(R.color.colorTextB));
            } else if (mList.get(position).getLb().equals("C")) {
                holder.lb.setTextColor(getResources().getColor(R.color.colorTextC));
            }
            holder.xm.setText(mList.get(position).getXlmc());
            holder.hb.setText(mList.get(position).getXbmc());
            holder.sgdd.setText(mList.get(position).getSgdd());
            holder.sgxm.setText(mList.get(position).getXmmc());
            holder.sgnr.setText(mList.get(position).getNrmc());
            holder.sgjx.setText(mList.get(position).getJxmc());
            holder.blfh.setText(mList.get(position).getBlfhmc());
            holder.sgdw.setText(mList.get(position).getSgdwmc());
            //B类防御 根据该计划类型是否为B类 判断是否显示
            if (mList.get(position).getLb().equals("B")) {
                holder.layout_blfh.setVisibility(View.VISIBLE);
            } else {
                holder.layout_blfh.setVisibility(View.GONE);
            }
            holder.zt.setText(mList.get(position).getZjhCxState());
            holder.zt.setTextColor(getContext().getResources().getColor(R.color.colorGreenTitle));

            //添加审核周计划列表状态点击事件
//            holder.zt.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
//            holder.zt.getPaint().setAntiAlias(true);//抗锯齿
//            holder.zt.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    SgzjhCkshjlActivity.mRowsBean = mList.get(position);
//                    Intent intent = new Intent(getActivity(), SgzjhCkshjlActivity.class);
//                    intent.putExtra("flags", "flags");
//                    startActivity(intent);
//                }
//            });
            holder.tablelayout.setOnClickListener(new View.OnClickListener() { //图片按钮的点击事件
                @Override
                public void onClick(View v) {
                    bh = mList.get(position).getBh();
                    Intent intent = new Intent(getContext(), SgzjhShenheDetailActivity.class);
                    intent.putExtra("bh", bh);
                    startActivity(intent);
                }
            });
            holder.btnShlc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SgzjhCkshjlActivity.mRowsBean = mList.get(position);
                    Intent intent = new Intent(getActivity(), SgzjhCkshjlActivity.class);
                    intent.putExtra("flags", "flags");
                    startActivity(intent);
                }
            });
            return convertView;
        }

        @SuppressWarnings("unused")
        class ViewHolder {
            //序号,周计划号,施工日期,类别,线名,行别,施工地点,施工项目,施工内容,施工机械
            //B类防护,施工单位,状态,隐藏的
            TextView xh, yjhh, sgrq, lb, xm, hb, sgdd, sgxm, sgnr, sgjx, blfh, sgdw, zt, tv_jhsh,  btnShlc;
            //操作按钮图片
            ImageView mImageView, flagImg;
            //B类防御layout
            LinearLayout layout_blfh,tablelayout;
        }

    }

    //设置条件搜索的Post参数
    private  Map<String,String> setMap(   Map<String,String> map, ZjhshSearchBean Bean) {
            if (Bean.getSglb() != null && !Bean.getSglb().equals("")) { //施工类别
                if (Bean.getSglb().equals("B"))
                    map.put("searchSgLb", "B");
                if (Bean.getSglb().equals("C"))
                    map.put("searchSgLb", "C");
            }
            if (Bean.getJhh() != null && !Bean.getJhh().equals("")) { //计划号
                map.put("searchBh", mSearchBean.getJhh());
            }
            if (Bean.getKsrq() != null && !Bean.getKsrq().equals("")) { //开始日期
                map.put("searchStartDay", mSearchBean.getKsrq());
            }
            if (Bean.getJsrq() != null && !Bean.getJsrq().equals("")) { //结束日期
                map.put("searchEndDay", mSearchBean.getJsrq());
            }
            if (Bean.getXlmc() != null && !Bean.getXlmc().equals("")) { //线路名称
                map.put("searchXlMc", mSearchBean.getXlmc());
            }
            if (Bean.getDwhbmId() != null && !Bean.getDwhbmId().equals("")) { //施工单位
                map.put("searchDwId", mSearchBean.getDwhbmId());
            }

        return map;
    }

}
